package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ExceptionUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.converter.ProductCateConverter;
import com.cskaoyan.shopping.dal.entitys.*;
import com.cskaoyan.shopping.dal.persistence.*;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

import static com.cskaoyan.shopping.constants.GlobalConstants.HEADER_PANEL_ID;
import static com.cskaoyan.shopping.constants.GlobalConstants.RECOMMEND_PANEL_ID;

/**
 * @program: duolaimall
 * @description:
 * @author: Lexis
 * @create: 2022-05-19 16:22
 **/
@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;


    @Override
    public HomePageResponse homepage() {
        HomePageResponse homePageResponse = new HomePageResponse();

        try {
            Example example = new Example(Panel.class);
            example.setOrderByClause("sort_order");
            example.createCriteria().andEqualTo("position", 0);
            List<Panel> panels = panelMapper.selectByExample(example);
            List<PanelDto> panelDtos = contentConverter.panelToDto(panels);
            for (PanelDto panel : panelDtos) {
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
                // 限制条目，多了就去掉最后一个
                if (panelContentItemDtos.size() > panel.getLimitNum()) {
                    panelContentItemDtos.remove(panelContentItemDtos.size() - 1);
                }
                panel.setPanelContentItems(panelContentItemDtos);
            }
            homePageResponse.setPanelContentItemDtos(panelDtos);
            homePageResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            homePageResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(homePageResponse, e);
        }
        return homePageResponse;
    }


}
